use crate::generators::{Generator, xmake_generator::XmakeGenerator};
use crate::parsers::{Parser, vs_parser::VsParser};
use crate::config::Config;
use crate::Result;
use std::collections::HashMap;
use std::path::Path;

pub struct Converter {
    parsers: HashMap<String, Box<dyn Parser>>,
    generators: HashMap<String, Box<dyn Generator>>,
}

impl Converter {
    pub fn new() -> Self {
        let mut converter = Self {
            parsers: HashMap::new(),
            generators: HashMap::new(),
        };
        
        // 注册默认的解析器和生成器
        converter.register_parser("vs".to_string(), Box::new(VsParser::new()));
        converter.register_generator("xmake".to_string(), Box::new(XmakeGenerator::new()));
        
        converter
    }
    
    pub fn with_config(config: &Config) -> Self {
        let mut converter = Self {
            parsers: HashMap::new(),
            generators: HashMap::new(),
        };
        
        // 注册带配置的解析器和生成器
        converter.register_parser("vs".to_string(), 
            Box::new(VsParser::with_env_config(config.environment_variables.clone())));
        converter.register_generator("xmake".to_string(), Box::new(XmakeGenerator::new()));
        
        converter
    }
    
    pub fn register_parser(&mut self, name: String, parser: Box<dyn Parser>) {
        self.parsers.insert(name, parser);
    }
    
    pub fn register_generator(&mut self, name: String, generator: Box<dyn Generator>) {
        self.generators.insert(name, generator);
    }
    
    pub fn convert(&self, input_path: &Path, generator_name: &str, project_root: &Path, config: &Config) -> Result<()> {
        // 根据文件扩展名自动选择解析器
        let parser = self.select_parser(input_path)?;

        // 解析输入文件
        log::info!("Parsing input file: {}", input_path.display());
        let solution = parser.parse(input_path)?;

        log::info!("Project root: {}", project_root.display());

        // 获取生成器
        let generator = self.generators.get(generator_name)
            .ok_or_else(|| crate::BuildMigrateError::Generator(
                format!("Unknown generator: {}", generator_name)
            ))?;

        // 生成输出文件
        log::info!("Generating output with {} generator", generator_name);
        generator.generate(&solution, project_root, &config.code_style)?;

        log::info!("Conversion completed successfully");
        Ok(())
    }
    
    fn select_parser(&self, input_path: &Path) -> Result<&Box<dyn Parser>> {
        let extension = input_path.extension()
            .and_then(|s| s.to_str())
            .ok_or_else(|| crate::BuildMigrateError::UnsupportedFormat(
                "No file extension".to_string()
            ))?;
        
        // 目前只支持Visual Studio格式
        for parser in self.parsers.values() {
            if parser.supported_extensions().contains(&extension) {
                return Ok(parser);
            }
        }
        
        Err(crate::BuildMigrateError::UnsupportedFormat(
            format!("No parser available for extension: {}", extension)
        ))
    }
    
    pub fn list_generators(&self) -> Vec<&String> {
        self.generators.keys().collect()
    }
    
    pub fn list_parsers(&self) -> Vec<&String> {
        self.parsers.keys().collect()
    }
}

impl Default for Converter {
    fn default() -> Self {
        Self::new()
    }
}
